package com.yixing.tech.system.dao;

import com.yixing.tech.common.base.BaseMongoDao;
import com.yixing.tech.system.po.Menu;
import com.yixing.tech.common.utils.DataUtil;
import com.yixing.tech.common.vo.s3.MenuVO;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yixing tech
 * * @date 2022/1/5
 */
@Repository
public class MenuDao {

    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private BaseMongoDao baseMongoDao;

    public void addChild(MenuVO vo) {

        Menu parent = baseMongoDao.get(vo.getParentId(), Menu.class);
        Menu dict = DataUtil.o2o(vo, Menu.class);
        if(dict.getStyle() ==null)dict.setStyle(0);
        dict = baseMongoDao.save(dict);
        List<Menu> list = parent.getChildren();
        if (list == null) {
            list = new ArrayList<>();
            parent.setChildren(list);
        }
        Menu child = new Menu();
        child.setId(dict.getId());
        list.add(child);
        baseMongoDao.update(parent);
    }
    public void deleteChild(String parentId, String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(parentId));
        Update update = new Update();
        //文档内嵌
        update.pull("children", Query.query(Criteria.where("_id").is(new ObjectId(id))));
        mongoTemplate.upsert(query, update, Menu.class);
    }


    /**
     * 绑定子菜单
     * @param parentId
     * @param childId
     */
    public void addExistedChild(String parentId,String childId) {

        Menu parent = baseMongoDao.get(parentId, Menu.class);
        List<Menu> list = parent.getChildren();
        if (list == null) {
            list = new ArrayList<>();
            parent.setChildren(list);
        }else{
            for(Menu menu:list){
                if(childId.equals(menu.getId()))return;
            }
        }
        Menu child = new Menu();
        child.setId(childId);
        list.add(child);
        baseMongoDao.update(parent);
    }



}
